package beans;

import java.io.File;
import java.io.PrintWriter;
import java.util.Iterator;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class FileUpload {
	public static final String UPLOAD_AVATAR_DIRECTORY = "avatar";
	public static final int THRESHOLD_SIZE = 1024 * 1024 * 3; // 3MB
	public static final int MAX_FILE_SIZE = 1024 * 1024 * 40; // 40MB
	public static final int MAX_REQUEST_SIZE = 1024 * 1024 * 50; // 50MB

	public static String uploadFile(HttpServletRequest request,
			HttpServletResponse response, String dirUpload) throws Exception {
		// checks if the request actually contains upload file
		if (!ServletFileUpload.isMultipartContent(request)) {
			PrintWriter writer = response.getWriter();
			writer.println("Request does not contain upload data");
			writer.flush();
			return null;
		}

		// configures upload settings
		DiskFileItemFactory factory = new DiskFileItemFactory();
		factory.setSizeThreshold(THRESHOLD_SIZE);
		factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
		// factory.setRepository(new File("member/avatar"));

		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setFileSizeMax(MAX_FILE_SIZE);
		upload.setSizeMax(MAX_REQUEST_SIZE);

		// constructs the directory path to store upload file
		// String uploadPath = getServletContext().getRealPath("")
		// + File.separator + UPLOAD_DIRECTORY;
		// System.out.print(uploadPath);

		// creates the directory if it does not exist
		File uploadDir = new File(dirUpload);
		if (!uploadDir.exists()) {
			uploadDir.mkdir();
		}

		File storeFile = null;
		// try {
		// parses the request's content to extract file data
		List<FileItem> formItems = upload.parseRequest(request);
		Iterator<FileItem> iter = formItems.iterator();
		// iterates over form's fields
		while (iter.hasNext()) {
			FileItem item = iter.next();
			// processes only fields that are not form fields
			if (!item.isFormField()) {
				String fileName = new File(item.getName()).getName();
				String filePath = dirUpload + File.separator
						+ System.currentTimeMillis() + getExtendtion(fileName);
				storeFile = new File(filePath);
				System.out.println(storeFile.getAbsolutePath());

				// saves the file on disk
				item.write(storeFile);
			}
		}
		// } catch (FileUploadException ex) {
		// throw new Exception(ex.getMessage());
		// } catch (Exception ex) {
		//
		// }
		return storeFile.getName();
	}

	public static String getExtendtion(String fileName) {
		String ext = null;
		try {
			ext = fileName.substring(fileName.lastIndexOf('.'));
		} catch (StringIndexOutOfBoundsException e) {
			ext = ".png";
		}
		return ext;
	}
}
